const Role = require('../models/role');

/**
 * 获取所有角色
 * @param {number} pageSize 每页条数
 * @param {number} page 页码
 * @param {string} searchKey 搜索关键词
 * @returns  {Promise<Object>} {roles,total,page,pageSize,searchKey}
 */
const getAllRoles = async ({page, pageSize, searchKey, all = 0}) => {

  try {
    if(all){
      const list = await Role.find();
      return {
        lists: list.map(item => {
          return {
            id: item._id,
            name: item.name,
            description: item.description,
            permissions: item.permissions,
            createdAt: item.createdAt,
            updatedAt: item.updatedAt,
            isAdmin: item.isAdmin,
            active: item.active,
            menus:item.menus
          }
        }),
        total: list.length
      }
    }

    const skip = (page - 1) * pageSize;
    const query = {};
    if (searchKey) {
      query.$or = [
        { name: { $regex: searchKey, $options: 'i' } },
        { description: { $regex: searchKey, $options: 'i' } }
      ];
    }
    const list = await Role.find(query).skip(skip).limit(pageSize);
    // 转换id
    
    const lists = list.map(item => {
      return {
        id: item._id,
        name: item.name,
        description: item.description,
        permissions: item.permissions,
        createdAt: item.createdAt,
        updatedAt: item.updatedAt,
        isAdmin: item.isAdmin,
        active: item.active,
        menus:item.menus
      }
    });
    const total = await Role.countDocuments(query);
    return {
      lists,
      total
    };
  } catch (error) {
    throw error.message;
  }
}

/**
 * 添加角色
 * @param {string} name 角色名称
 * @param {string} description 角色描述
 * @param {string[]} permissions 角色权限
 * @returns {Promise<Object>} 新创建的角色
 */
const addRole = async (name, description, permissions = []) => {
  try {
    const findRole = await Role.findOne({ name: name });
    if (findRole) {
      throw new Error('Role already exists');
    }
    const newRole = await Role.create({
      name: name,
      description: description,
      permissions: permissions
    });
    return newRole;
  } catch (error) {
    throw error.message;
  }
};

/**
 * 更新角色
 * @param {string} id 角色ID
 * @param {string} name 角色名称
 * @param {string} description 角色描述
 * @param {string[]} permissions 角色权限
 * @returns {Promise<Object>} 更新后的角色
 */
const updateRole = async (id, name, description, permissions = [] ,active) => {

  try {
    const findRole = await Role.findById(id);
    if (!findRole) {
      throw new Error('Role not found');
    }
    if(findRole.isAdmin && active === false){
      throw new Error('不能禁用默认角色');
    }

    findRole.name = name;
    findRole.description = description;
    if(permissions.length > 0){
      findRole.permissions = permissions;
    }
    findRole.updatedAt = Date.now();
    findRole.active = active;
    await findRole.save();
    return findRole;
  } catch (error) {
    throw error.message;
  }
}

/**
 * 删除角色
 * @param {string} id 角色ID
 * @returns {Promise<Object>} 删除的角色
 */
const deleteRole = async (id) => {
  try {
    const findRole = await Role.findById(id);
    if (!findRole) {
      throw new Error('没有找到该角色');
    }
    if(findRole.isAdmin){
      throw new Error('不能删除默认角色');
    }
    await findRole.deleteOne();
    return findRole;
  } catch (error) {
    throw error.message;
  }
}

/**
 * 获取角色权限
 * @param {string} id 角色ID
 * @returns {Promise<string[]>} 角色权限列表
 */
const getPermissions = async (id) => {
  try {
    const role = await Role.findById(id);
    if (!role) {
      throw new Error('角色不存在');
    }
    return role.permissions;
  } catch (error) {
    throw error.message;
  }
}

/**
 * 分配权限给角色
 * @param {string} id 角色ID
 * @param {string[]} permissions 权限列表
 * @returns {Promise<Object>} 更新后的角色
 */
const assignPermissions = async (id, permissions) => {
  try {
    const role = await Role.findById(id);
    if (!role) {
      throw new Error('角色不存在');
    }
    role.permissions = permissions;
    role.updatedAt = Date.now();
    await role.save();
    return role;
  } catch (error) {
    throw error.message;
  }
}

/**
 * 获取所有权限
 * @returns {Promise<string[]>} 所有权限列表
 */

const getAllPermissions = () => {
  try {
    console.log('Role.PERMISSIONS:', Role.PERMISSIONS);
    const list = Object.assign({}, Role.PERMISSIONS);
    console.log('getAllPermissions returning:', list);
    return list;
  } catch (error) {
    console.error('Error in getAllPermissions:', error);
    throw error.message;
  }
}
/**
 * 检查用户是否有指定权限
 * @param {Object} user 用户对象
 * @param {string} permission 权限名称
 * @returns {boolean} 是否有该权限
 */
const hasPermission = (user, permission) => {
 const { permissions } = Role.findOne({ _id: user.rid })
  // 检查用户是否拥有指定权限
  if (user && permissions.includes(permission)) {
    return true;
  }
  return false;
}
/**
 * 给角色分配菜单
 */
const assignMenus = async (id, menus) => {
  try {
    const role = await Role.findById(id);
    if (!role) {
      return {
        code: 201,
        message: '角色不存在'
      }
    }
    role.menus = menus;
    role.updatedAt = Date.now();
    await role.save();
    return {
      code: 200,
      message: '分配成功'
    }
  } catch (error) {
    return {
      code: 400,
      message: error.message
    }
  }
}
const getRoleMenus = async (id) => {
  try {
    const role = await Role.findById(id);
    if (!role) {
      return {
        code: 201,
        message: '角色不存在'
      }
    }
    return {
      code: 200,
      message: '获取成功',
      data: role.menus
    }
  } catch (error) {
    return {
      code: 400,
      message: error.message
    }
  }
}


module.exports = {
  addRole,getAllRoles,updateRole,deleteRole,hasPermission,getPermissions,assignPermissions,getAllPermissions,assignMenus,
  getRoleMenus
};